/*
    This is a set of libraries to assist in OpenGl and Other Applications
    Copyright (C) 2008  The Modular Engine Team

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#define IMAGELOADER
#include "ImageLoader.h"

// Functions for loading textures

namespace ModularEngine
{

	Texture LoadTextureFunc::operator ()(char *pPath)
	{
		return ImageLoader::getSingleton().LoadTexture( pPath );
	}

	Texture ImageLoader::LoadTexture( const char *pTexturePath)
	{
		Texture nTex;


		FREE_IMAGE_FORMAT fType = FreeImage_GetFileType( pTexturePath );

		FIBITMAP *img = FreeImage_Load( fType, pTexturePath, 0 );
		if( !img )
		{
			//cout << "Load Unsuccessful" << endl;
			return Texture();
		}

		nTex.mBpp = FreeImage_GetBPP( img )/8;
		nTex.mWidth = FreeImage_GetWidth( img );
		nTex.mHeight = FreeImage_GetHeight( img );
		
		RGBQUAD pixel;
		nTex.mData = new unsigned char[nTex.mWidth*nTex.mHeight*nTex.mBpp];
		int val = 0;
		for( int j = 0; j < nTex.mHeight; j++ )
			for( int i = 0; i < nTex.mWidth; i++ )
			{
				FreeImage_GetPixelColor( img, i, j, &pixel ); 
				nTex.mData[val*nTex.mBpp] = pixel.rgbRed;
				nTex.mData[val*nTex.mBpp+1] = pixel.rgbGreen;
				nTex.mData[val*nTex.mBpp+2] = pixel.rgbBlue;
				val++;
				if( nTex.mBpp == 4 )
					nTex.mData[val*nTex.mBpp+3] = pixel.rgbReserved;
			}

		FreeImage_Unload( img );

		return nTex;
	}
}
